import React from "react";
import MainLayout from "../../../component/mainLayout/mainLayout";
import AgreeCheckbox from "../../../component/agreeCheckbox";
import PaypwdVerify from "../paypwdVerify/PaypwdVerify";
import yhTools from "../../../tools/yh";
import { InterfaceG } from "../../../config/Config";
import { Toast } from "antd-mobile";
import { ThemeDefault, ThemeLife } from "../../../tools/theme";

import "./SignXHB.scss";

class SignXHB extends React.Component {
	constructor(props) {
		super(props);
		/**
		 * 如果是原生进入充值界面,index_fromType = app
		 * 返回键直接关闭page
		 */
		let index_fromType = sessionStorage.getItem("index_fromType");
		let flag = index_fromType && index_fromType === "app";
		/**
		 * 判断是否是SignRes返回,如果是需要打开弹出层,并且同意协议
		 */
		let signres_page = sessionStorage.getItem("signres_page");
		sessionStorage.removeItem("signres_page");
		let isSignres_page = !!signres_page;

		this.state = {
			loadStatus: "1",
			/** 是否同意协议 */
			isConsent: isSignres_page,
			/**是否显示支付密码框 */
			payVisible: isSignres_page,
			/** 预估到账 */
			estimateToAccountAmount: "",
			/** 是否回退到app */
			flag
		};
		/** 界面类型 0是正常途径进入，1是还款进入*/
		this._pagetype = props.location.pathname.indexOf("xhb") === -1 ? 0 : 1;
	}

	componentDidMount() {
		this.initPage();
	}

	/** 检查是否设置支付密码 */
	async checkSetPassword() {
		let objs = {
			url: InterfaceG.xhbgetPassword,
			params: {},
			_alertShow: false
		};

		Toast.loading("加载中...", 100);
		let res = await yhTools.request(objs);
		Toast.hide();
		if (res.code === "0") {
			return res.data.status == "1";
		} else {
			// 异常状态返回上一页面
			Toast.info(res.message, 2);
			if (this.state.flag) {
				// 收银台过来
				yhTools.closePage();
			} else {
				// 小辉宝首页过来
				this.props.history.goBack();
			}
			return true;
		}
	}

	/** 初始化页面数据 */
	async initPage() {
		let isPwd = await this.checkSetPassword();
		if (!isPwd) {
			return this.props.history.replace({
				pathname: "/xhdsetPayPwd",
				state: { formType: "signXHB" }
			});
		}

		let objs = {
			url: InterfaceG.xhbPayEstimateToAccount,
			params: {},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		let res = await yhTools.request(objs);
		Toast.hide();
		if (res.code === "0") {
			this.setState({
				estimateToAccountAmount: res.data.estimateToAccountAmount
			});
		} else {
			Toast.info(res.message, 2);
		}
	}

	/** 发送验证码 */
	async sendSMSCode(startTimer) {
		let objs = {
			url: InterfaceG.applyXhbPaySign,
			params: {},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		let res = await yhTools.request(objs);
		Toast.hide();
		if (res.code === "0" || res.code === "30022") {
			startTimer();
			if (res.code === "30022") {
				Toast.info(res.message, 2);
			}
			return true;
		} else {
			Toast.info(res.message, 2);
			return false;
		}
	}

	/** 发起支付签约 */
	applyPaySign() {
		if (!this.state.isConsent) {
			return Toast.info("请阅读并同意《福建华通银行小辉宝支付服务协议》", 2);
		}

		this.setState({ payVisible: true });
	}

	/** 确认小辉包支付签约 */
	async confirmXhbPaySign(params) {
		let objs = {
			url: InterfaceG.confirmXhbPaySign,
			params,
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		let res = await yhTools.request(objs);
		Toast.hide();

		if (res.code === "0") {
			if (!res.data.errorMsg) {
				if (!this._pagetype) {
					this.props.history.push({ pathname: "/signRes" });
				} else {
					this.props.history.replace({
						pathname: `/xhbsignRes/${this.props.match.params.amount}`
					});
				}
			} else if (!this._pagetype) {
				this.props.history.push({
					pathname: "/signRes",
					state: { msg: res.data.errorMsg }
				});
			} else {
				this.props.history.replace({
					pathname: `/xhbsignRes/${this.props.match.params.amount}`,
					state: { msg: res.data.errorMsg }
				});
			}
		} else {
			Toast.info(res.message, 2);
		}
	}

	render() {
		const headerParams = {
			header: {
				title: "开通小辉宝支付",
				rightButt: (
					<img
						onClick={() => this.props.history.push({ pathname: "/xhbPayHelp" })}
						src={require("../../../images/imageXHB/signxhb-head-p.png")}
						style={{ width: "0.38rem", position: "relative", top: "0.06rem" }}
					/>
				),
				rightButtCallBack: () => {},
				goToApp: this.state.flag
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles,
			loadStatus: this.state.loadStatus // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败）
		};

		return (
			<MainLayout pageParams={headerParams}>
				<div className="signxhb-page">
					<div className="content">
						<div className="bg">
							<img
								src={require("../../../images/imageXHB/sign-headtitle.png")}
								alt=""
							/>
						</div>
						<div className="tip">
							{/* <img src={require('../../../images/imageXHB/signxhb-tip.png')} alt=""/> */}
							{this.state.estimateToAccountAmount && (
								<span>
									收益提示：已过观察期存单提前支取，按活期利率0.40%计息，电子账户预估到账
									{this.state.estimateToAccountAmount}元。
								</span>
							)}
						</div>
						<ul>
							<li>
								<div className="icon">
									<img
										src={require("../../../images/imageXHB/signxhb-img-1.png")}
										alt=""
									/>
								</div>
								<p>可直接支付</p>
								<span>本金及收益</span>
								<span>可用于买菜</span>
							</li>
							<li>
								<div className="icon">
									<img
										src={require("../../../images/imageXHB/signxhb-img-2.png")}
										alt=""
									/>
								</div>

								<p>一键支取</p>
								<span>多笔存款</span>
								<span>一键支取</span>
							</li>
							<li>
								<div className="icon">
									<img
										src={require("../../../images/imageXHB/signxhb-img-3.png")}
										alt=""
									/>
								</div>

								<p>自动合并存单</p>
								<span>多笔存单</span>
								<span>自动合成一笔</span>
							</li>
						</ul>
						<ThemeDefault>
							<div
								className="btn"
								style={{ opacity: this.state.isConsent ? 1 : 0.15 }}
								onClick={() => {
									this.applyPaySign();
								}}
							>
								立即开通
							</div>
						</ThemeDefault>
						<ThemeLife>
							<div
								className="btn a-gradient"
								style={{ opacity: this.state.isConsent ? 1 : 0.15 }}
								onClick={() => {
									this.applyPaySign();
								}}
							>
								立即开通
							</div>
						</ThemeLife>
					</div>
					<div className="xieyiwrap">
						<AgreeCheckbox
							checked={this.state.isConsent}
							onChange={() =>
								this.setState({ isConsent: !this.state.isConsent })
							}
						>
							<span className="xieyi">
								{" "}
								我阅读并同意
								<a
									onClick={() =>
										this.props.history.push({ pathname: "/signXHBXY" })
									}
								>
									《福建华通银行小辉宝支付服务协议》
								</a>
							</span>
						</AgreeCheckbox>
					</div>

					<div className="logo">
						<img
							src={require("../../../images/imageXHB/singxhb-logo.png")}
							alt=""
						/>
						<p>本服务由华通银行提供</p>
					</div>

					<PaypwdVerify
						visible={this.state.payVisible}
						title="支付密码+短信验证码"
						onClose={() => {
							this.setState({ payVisible: false });
						}}
						onSubmit={form => this.confirmXhbPaySign(form)}
						onSendSMSCode={cb => this.sendSMSCode(cb)}
					/>
				</div>
			</MainLayout>
		);
	}
}

export default SignXHB;
